<template>
  <div class="reset-pwd">
    <h1>重置密码</h1>
    <p>{{ resetPwdStatus ? "请先绑定手机或邮箱再重置密码" : "请设置新密码" }}</p>
    <el-form :model="form" :rules="rules" ref="ruleForm" status-icon>
      <div v-if="resetPwdStatus">
        <el-form-item prop="phoneOrEmail">
          <el-input placeholder="请输入手机号或邮箱地址" v-model.trim="form.phoneOrEmail"></el-input>
        </el-form-item>
        <el-form-item prop="slider" class="slider">
          <verify-slider
            v-model="form.slider"
            ref="slider"
            tips="请按住滑块，拖动到最后"
            @success="slideSuccess"
          ></verify-slider>
        </el-form-item>
        <el-form-item prop="identifyCode">
          <el-input v-model="form.identifyCode">
            <template slot="append">
              <el-button
                :disabled="identifyCodeMsg !== '获取验证码'"
                @click="getVCode"
              >{{ identifyCodeMsg }}</el-button>
            </template>
          </el-input>
          <div class="code-error" v-show="validateCodeError">验证码错误</div>
        </el-form-item>
      </div>
      <el-form-item prop="password" v-else>
        <!-- <el-input v-model.trim="form.password" placeholder="新密码" show-password></el-input> -->
        <validate-pwd v-model="form.password" @setPassword="setPassword"></validate-pwd>
      </el-form-item>
      <el-form-item class="black-btn">
        <el-button
          v-if="resetPwdStatus"
          @click="nextStep"
          :loading="loading"
          style="width: 400px;margin-top: 30px;"
        >下一步</el-button>
        <el-button v-else @click="confirm" style="width: 400px;margin-top: 30px;">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { VerifySlider } from 'vue-verify-slider'
import ValidatePwd from '@/components/ValidatePwd'
export default {
  components: {
    VerifySlider,
    ValidatePwd
  },
  props: {
    userInfo: {
      type: Object,
      default: () => { }
    }
  },
  data() {
    // 验证输入的手机号或邮箱
    const validatePhoneOrEmail = (rule, value, callback) => {
      const phoneReg = /^1(3|4|5|7|8)\d{9}$/
      const emailReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-_.])+[A-Za-z]{2,5}$/
      if (!value) {
        return callback(new Error('请输入手机号或邮箱地址'))
      } else if (!phoneReg.test(value) && !emailReg.test(value)) {
        return callback(new Error('请输入正确的手机号或邮箱地址'))
      } else {
        if (phoneReg.test(value)) {
          const params = {
            mobileNumber: value
          }
          this.$http.post(this.$service.checkPhoneNumber, params).then(res => {
            if (res.value) {
              return callback(new Error('该手机/邮箱已被其他账号绑定'))
            } else {
              return callback()
            }
          })
        } else {
          const params = {
            email: value
          }
          this.$http.post(this.$service.checkEmail, params).then(res => {
            if (res.value) {
              return callback(new Error('该手机/邮箱已被其他账号绑定'))
            } else {
              return callback()
            }
          })
        }
      }
    }
    const validatePwd = (rule, value, callback) => {
      const reg = /(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,20}$/
      const reg2 = /^[^ ]+$/ // 判断密码是否包含空格
      if (!value) {
        return callback(new Error('密码不能为空'))
      } else if (!reg2.test(value)) {
        return callback(new Error('密码只能包含数字字母、标点符号（空格除外）'))
      } else if (value.length < 6 || value.length > 20) {
        return callback(new Error('密码长度需为6-20个字符'))
      } else if (!reg.test(value)) {
        return callback(new Error('密码强度不符合要求'))
      } else {
        return callback()
      }
    }
    const validateIdentifyCode = (rule, value, callback) => {
      if (!value) {
        this.validateCodeError = false
        return callback(new Error('验证码不能为空'))
      } else {
        return callback()
      }
    }
    const validateSlider = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请完成人机验证'))
      } else {
        return callback()
      }
    }
    return {
      form: {
        phoneOrEmail: '',
        slider: false,
        password: ''
      },
      identifyCodeMsg: '获取验证码',
      rules: {
        phoneOrEmail: [{ validator: validatePhoneOrEmail, trigger: 'blur' }],
        identifyCode: [{ validator: validateIdentifyCode, trigger: 'blur' }],
        slider: [{ validator: validateSlider }],
        password: [{ validator: validatePwd, trigger: 'blur' }]
      },
      resetPwdStatus: true,
      validateCodeError: false,
      loading: false
    }
  },
  methods: {
    nextStep() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.loading = true
          const params = {
            uname: this.form.phoneOrEmail,
            vCode: this.form.identifyCode,
            pid: 210
          }
          this.$http.post(this.$service.validateVCode, params).then(res => {
            this.validateCodeError = !res.data.validate
            if (res.data.validate) {
              const phoneReg = /^1(3|4|5|7|8)\d{9}$/
              const params = {
                uid: this.userInfo.uid,
                realname: this.userInfo.uname,
                tel: phoneReg.test(this.form.phoneOrEmail) ? this.form.phoneOrEmail : '',
                email: !phoneReg.test(this.form.phoneOrEmail) ? this.form.phoneOrEmail : ''
              }
              this.$http.post(this.$service.updateUserInfo, params)
              this.resetPwdStatus = false
            }
          }).finally(() => {
            this.loading = false
          })
        }
      })
    },
    setPassword(value) {
      this.form.password = value
    },
    slideSuccess() {
      this.form.slider = true
      this.$el.querySelector('.slider .el-form-item__error').style.display = 'none'
    },
    getVCode() {
      this.$refs.ruleForm.validateField('phoneOrEmail', valid => {
        if (!valid) {
          this.$refs.ruleForm.validateField('slider', () => {
            if (this.form.slider) {
              let time = 60
              let timer = setInterval(() => {
                this.identifyCodeMsg = time + 's 后重新获取'
                time--
                if (time < 0) {
                  clearInterval(timer)
                  this.identifyCodeMsg = '获取验证码'
                }
              }, 1000)
              const params = {
                uname: this.form.phoneOrEmail,
                pid: 210
              }
              this.$http.post(this.$service.getVCode, params).then(res => {
                const vCode = res.data.vCode
                const phoneReg = /^1(3|4|5|7|8)\d{9}$/
                if (phoneReg.test(this.form.phoneOrEmail)) {
                  const info = {
                    appId: 'cue_frontend',
                    appToken: 'c890195cd04f0afffcc118812d83dca6',
                    mobiles: [
                      this.form.phoneOrEmail
                    ],
                    msgContent: `尊敬的用户，本次操作验证码：${vCode}，10分钟内有效，请勿泄露。`,
                    msgSignature: '【开域集团】'
                  }
                  this.$http.post(this.$service.sendPhoneVCode, info)
                } else {
                  const params = {
                    email: this.form.email,
                    title: 'test',
                    content: `尊敬的用户，本次操作验证码：${vCode}，10分钟内有效，请勿泄露。`,
                    emailAddress: 'dvp_service@cue.group',
                    emailAddressName: '开域集团',
                    password: 'Abcd56789'
                  }
                  this.$http.post(this.$service.sendEmailCode, params)
                }
              })
            }
          })
        }
      })
    },
    confirm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = {
            uid: this.userInfo.uid,
            password: this.form.password
          }
          this.$http.post(this.$service.updateUserPwd, params).then(res => {
            if (res.message === '成功') {
              this.$router.push({
                path: '/validateSuccess',
                query: {
                  state: 'modifyPwd'
                }
              })
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.reset-pwd {
  h1 {
    font-size: 30px;
    margin: 0;
  }
  p {
    font-size: 16px;
    color: #aaa;
    margin-bottom: 40px;
  }
  .code-error {
    font-size: 12px;
    color: #f56c6c;
    line-height: 1;
    position: absolute;
    top: 45px;
  }
  .drag {
    width: 100%;
    .drag_bg {
      width: 100% !important;
    }
  }
}
</style>
